# Author: ngoet
# First version: 24.8.2018
# This version: 7.12.2018
# Replication file for: Goet, Fleming, and Zubek, 2018


dataPath <- gsub('runReplication.R','',rstudioapi::getSourceEditorContext()$path)

setwd(dataPath)
sink("log_runReplication.log", append=TRUE, split=TRUE) 

system('mkdir output')
system('mkdir output/tables')
system('mkdir output/figures')


# Dependencies (please uncomment the lines below to install the required R dependencies)
# dependencies <- c('texreg', 'xtable', 'sandwich', 'ggplot2', 'pscl', 'countreg', 'stringr', 'ngram', 'stargazer', 'lmtest', 'arm', 'zoo', 'grid', 'gridExtra', 'DataCombine', 'MASS')

# lapply(dependencies,function(x) install.packages(x))

# set up log file
logfile_name <- gsub('-| |:','_',paste('ukhcso_logfile_',Sys.time(),'.log',sep=''))
log_file <- file(logfile_name)
cat(paste('Starting replication for main analysis (start time: ',Sys.time(),')',sep=''),file=log_file)
close(log_file)

#execution function
execute_script <- function(print_message,script_name,type="R",input_params=NULL,numCores=NULL){
  message(print_message)
  log_file <- file(logfile_name, open = 'a')
  cat(paste('\n\nExecuting ',script_name,' script (start time: ',Sys.time(),')',sep=''), file = log_file,append = TRUE)
  close(log_file)

  if(type=="R"){
    execution_time <- round(system.time({source(script_name)})[3]/60,digits=2)
  }else{
    execution_time <- round(system.time({system(paste('python3',script_name,input_params,sep=' '))})[3]/60,digits=2)  
  }

  log_file <- file(logfile_name, open = 'a')
  cat(paste('\n',script_name, ' script successfully run. Execution time: ',execution_time," minutes",sep=''), file = log_file,append = TRUE)
  close(log_file)
  
  message(paste('\n',script_name, ' script successfully run. Execution time: ',execution_time," minutes",sep=''))
  
}

# Replicate empirical analysis
print_message <- 'Replicating empirical analysis'
script_name <- 'dependencies/hurdleModelsAnalysis.R'
  
execute_script(print_message,script_name)


# Replicate Figures and tables
print_message <- 'Replicating figures'
script_name <- 'dependencies/genFiguresTables.R'

execute_script(print_message,script_name)

